﻿# -*- coding: utf-8 -*-
# @Time : 2022/8/14 15:47
# @Author : Dong
# @File : test.py
import traceback
from datetime import datetime

import Iciba
import uvicorn
from fastapi import FastAPI
from apscheduler.schedulers.asyncio import AsyncIOScheduler
import requests
from requests.adapters import HTTPAdapter

app = FastAPI(title='fast-api')

scheduler = None


def job():
    holiday = {
        "01-01": "尊敬的漂亮悦宝贝! 元旦节快乐!",
        "01-24": "国色天香大公主! 春节快乐!过年好!",
        "04-05": "清明节祭奠、缅怀先人啦，宝贝!",
        "03-08": "我的悦悦爱人! 妇女节快乐!",
        "05-01": "My Dear悦! 劳动节快乐!",
        "06-03": "小粽子节快乐! 可爱性感...集一身",
        "06-01": "我那乖巧的小悦悦! 永远是个小孩子呢!",
        "09-10": "叶大人! 叶大美人! 中秋节快乐!",
        "10-01": "大大大大大大漂亮小公主! 国庆节快乐!",
        "08-04": "我的大情人小公主! 我的情人节怎么能没有你呢!",
        "02-14": "情人节快乐! 我的好悦悦女王殿下!",
        "12-25": "天下最漂亮的悦仙女! 圣诞节快乐!",
    }
    # 微信配置
    wechat_config = {
        'appid': 'wx08d0d39045f2ee19',  # (No.1)此处填写公众号的appid
        'appsecret': '37934544c2e9ee12bc4532817c9f6f10',  # (No.2)此处填写公众号的appsecret
    }

    template_params = {
        "Mt4aHzEJBkcJEcXwROPVp-cqk_ig9lRh7GQHHpzZI-8": {
            "target_linZheng": '2025-05-20',  # 领证日期
            'target_shengRi': '1998-12-27',  # 生日
            'target_jieHun': '2025-05-20',  # 结婚日期,
            'target_lianAi': '2023-03-11',  # 恋爱日期,
            'weather_ak': 'GCjhFlEGXt3kiWYKvO7wjgITOZ9mSgqI',  # 百度天气
            'tian_caihongpi_key': 'a5f857943900f45953b79d975fd96c2d',  # 天行彩虹屁 https://www.tianapi.com/apiview/181
            'mark': holiday.get(datetime.now().strftime("%m-%d")) if holiday.get(
                datetime.now().strftime("%m-%d")) else "",
            "district_id": "330109",  # 女朋友所在的区域代码
            "girl_name": "ysy"  # 女朋友名字的大写字母
        }
    }

    # 用户列表
    openids = [
        { "template_id" : "Mt4aHzEJBkcJEcXwROPVp-cqk_ig9lRh7GQHHpzZI-8", "open_id" : 'oNOOZ6NgOYxOOoLv2dFD2-Sn-SRI'},  # 微信公众平台上的微信号  :  此处填写公众号的模板消息ID
        {"open_id" : 'oNOOZ6LLP_5V1BOJbWbGn2-9Fhxg', "template_id" : "Mt4aHzEJBkcJEcXwROPVp-cqk_ig9lRh7GQHHpzZI-8"},
        # 'xxxxx', #如果有多个用户也可以
        # 'xxxxx',
    ]

    # 执行
    icb = Iciba.iciba(wechat_config, template_params)

    '''
    run()方法可以传入openids列表，也可不传参数
    不传参数则对微信公众号的所有用户进行群发
    '''
    icb.run(openids=openids)


@app.get('/push')
async def push_wechat():
    """添加job"""
    try:
        job()
    except Exception as e:
        traceback.format_tb(15)
        return {"msg": "fail"}
    return {"msg": "success!"}

def get_push():
    s = requests.Session()
    s.mount('http://', HTTPAdapter(max_retries=3))

    resp = s.get('http://127.0.0.1:9999/push')
    if resp.status_code == 200:
        print("push成功")
    else:
        print("push失败")


@app.on_event('startup')
def init_scheduler():
    """初始化"""
    global scheduler
    scheduler = AsyncIOScheduler(timezone='Asia/Shanghai')
    scheduler.add_job(get_push, 'cron', hour='10', minute='00', misfire_grace_time=120)
    print("启动调度器...")
    scheduler.start()


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=9999)
